package org.hank.compose_yyzs.viewmodel

import android.content.Context
import androidx.constraintlayout.compose.ConstraintSet
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectIndexed
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.hank.compose_yyzs.MyApp
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.bean.MerchantInfo
import org.hank.compose_yyzs.bean.WifiBean
import org.hank.compose_yyzs.constants.Constants
import org.hank.compose_yyzs.db.MyDatabase
import org.hank.compose_yyzs.db.dao.WifiDao
import org.hank.compose_yyzs.http.ApiService
import org.hank.compose_yyzs.utils.NetWorkUtils
import org.hank.compose_yyzs.utils.NetWorkUtils.generateMessageByException
import java.io.File
import javax.inject.Inject

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/8/22 16:14
 *描述:
 */
@HiltViewModel
class SettingViewModel @Inject constructor(
    var apiService: ApiService,
    var wifiDao: WifiDao
) : ViewModel() {
    var testerName = MutableStateFlow("")
    var customerName = MutableStateFlow("")
    var currentWifiAddress = MutableStateFlow("")
    var telantName = MutableStateFlow("")
    var cache = MutableStateFlow("")

    var showTips = MutableStateFlow(false)
    var showTipsContent = MutableStateFlow("")
    var tipsConfirm: () -> Unit = {}

    private val _viewEvents = Channel<SettingViewEvent>(Channel.BUFFERED)
    val viewEvents = _viewEvents.receiveAsFlow()

    fun clearCache() {
        viewModelScope.launch {
            showTips.emit(false)
            MyApp.context.cacheDir.listFiles()?.forEach { file ->
                file.deleteRecursively()
            }
            wifiDao.delAll()
            getCache(MyApp.context)
            _viewEvents.send(SettingViewEvent.ClearCacheSuccess)
        }
    }

    fun getCache(context: Context) {
        var size: Long = 0
        size = getDirectorySize(context.cacheDir.absolutePath)
        Logger.d("cache size $size")
        viewModelScope.launch {
            cache.emit("${size / 1024 / 1024}")
        }
    }

    suspend fun updateCurrentWifi() {
        var wifiBean = wifiDao.currentWifiInfo
        currentWifiAddress.emit(wifiBean?.wifiAddress ?: "")
    }

    fun getUserInfo() {
        viewModelScope.launch {
            var userId = MMKV.defaultMMKV().getInt(Constants.USER_ID,-1)
            flow { emit(apiService.getUserInfo(userId)) }
                .catch {
                   _viewEvents.send(SettingViewEvent.ErrorMessage(generateMessageByException(it)))
                }
                .collect {
                    testerName.value = it.data.name?:""
                    customerName.value = it.data.departMentName?:""

                    flow { emit(apiService.getTenantNameById(it.data.tenantId.toString())) }
                        .catch {
                            _viewEvents.send(SettingViewEvent.ErrorMessage(generateMessageByException(it)))
                        }.collect{
                            telantName.emit(it.data.name ?: "")
                        }
            }
        }
    }

    private fun getDirectorySize(path: String): Long {
        var totalSize: Long = 0
        val directory = File(path)
        if (directory.exists() && directory.isDirectory()) {
            val files = directory.listFiles()
            if (files != null) {
                for (file in files) {
                    if (file.isFile()) {
                        totalSize += file.length()
                    } else if (file.isDirectory()) {
                        totalSize += getDirectorySize(file.absolutePath)
                    }
                }
            }
        }
        return totalSize
    }
}

sealed class SettingViewEvent {
    object ClearCacheSuccess : SettingViewEvent()

    data class ErrorMessage(val message: String) : SettingViewEvent()
}